<template>
  <div>
    <h2>全校活动及社团统计</h2>
    <div id="charts">
      <div id="line-chart-clubs" style="width: 600px; height: 400px;"></div>
      <div id="line-chart-activities" style="width: 600px; height: 400px;"></div>
    </div>
    <div id="tables">
      <div id="club-table" v-if="showClubsTable" style="display: flex; position: relative;">
        <table>
          <thead>
            <tr>
              <th>社团名称</th>
              <th>社团类型</th>
              <th>社团规模</th>
              <th>
                <select v-model="selectedGenderRatio" style="font-size: inherit; font-weight: inherit; border: none; background-color: transparent;">
                  <option value="male">男生占比</option>
                  <option value="female">女生占比</option>
                </select>
              </th>
              <th>党员人数</th>
              <th>党员占比</th>
              <th>举办活动数</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="club in clubs" :key="club.Cid" @mouseover="showClubDetails = true; updateClubDetailsCharts(club); updateHoverPosition($event)" 
        @mousemove="updateHoverPosition($event)" 
        @mouseleave="showClubDetails = false">
              <td>{{ club.Cname }}</td>
              <td>{{ getTypeText(club.Type) }}</td>
              <td>{{ club.Size }}</td>
              <td>
                <template v-if="selectedGenderRatio === 'male'">{{ club.Gender0Ratio }}%</template>
                <template v-else>{{ club.Gender1Ratio }}%</template>
              </td>
              <td>{{ club.PartyMemberCount }}</td>
              <td>{{ club.PartyMemberRatio }}%</td>
              <td>{{ club.Activities }}</td>
            </tr>
          </tbody>
        </table>
        <div v-if="showClubsTable" style="display: flex; flex-direction: column;">
          <div id="club-type-pie" style="width: 300px; height: 300px; "></div>
          <div id="club-size-pie" style="width: 300px; height: 300px; "></div>
        </div>
        <div v-if="showClubDetails" class="hover-panel" :style="{ display: 'flex', position: 'absolute', top: hoverPosition.top + 'px', left: hoverPosition.left + 'px', gap: '20px' }">
          <!-- 社团详细信息的图表展示 -->
          <div id="club-gender-pie" class="chart"></div>
          <div id="club-grade-pie" class="chart"></div>
          <div id="club-party-pie" class="chart"></div>
          <div id="club-major-pie" class="chart"></div>
          <div id="club-yearly-line" class="chart"></div>
        </div>
      </div>
      <div id="activity-table" v-if="showActivitiesTable" style="display: flex; position: relative;">
        <table>
          <thead>
            <tr>
              <th>活动名称</th>
              <th>活动类型</th>
              <th>活动规模</th>
              <th>
                <select v-model="selectedGenderRatio" style="font-size: inherit; font-weight: inherit; border: none; background-color: transparent;">
                  <option value="male">男生占比</option>
                  <option value="female">女生占比</option>
                </select>
              </th>
              <th>党员人数</th>
              <th>党员占比</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="activity in activities" :key="activity.Aid" @mouseover="showActivityDetails = true; updateActivityDetailsCharts(activity); updateHoverPosition($event)" @mouseleave="showActivityDetails = false">
              <td>{{ activity.ATitle }}</td>
              <td>{{ getTypeText(activity.Type) }}</td>
              <td>{{ activity.Size }}</td>
              <td>{{ selectedGenderRatio === 'male' ? activity.Gender0Ratio : activity.Gender1Ratio }}%</td>
              <td>{{ activity.PartyMemberCount }}</td>
              <td>{{ activity.PartyMemberRatio }}%</td>
            </tr>
          </tbody>
        </table>
        <div v-if="showActivitiesTable" style="display: flex; flex-direction: column;">
          <div id="activity-type-pie" style="width: 300px; height: 300px; "></div>
          <div id="activity-size-pie" style="width: 300px; height: 300px; "></div>
        </div>
        <div v-if="showActivityDetails" class="hover-panel" :style="{ display: 'flex', position: 'absolute', top: hoverPosition.top + 'px', left: hoverPosition.left + 'px', gap: '20px' }">
          <!-- 活动详细信息的图表展示 -->
          <div id="activity-gender-pie" class="chart"></div>
          <div id="activity-grade-pie" class="chart"></div>
          <div id="activity-party-pie" class="chart"></div>
          <div id="activity-major-pie" class="chart"></div>
          <div id="activity-yearly-line" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  data() {
    return {
      years: [],
      selectedYear: null,
      clubs: [],
      activities: [],
      showClubsTable: true,
      showActivitiesTable: false,
      showClubDetails: false,
      showActivityDetails: false,
      selectedGenderRatio: 'male',
      hoverPosition: {
        top: 0,
        left: 0
      },
    };
  },
  mounted() {
    this.fetchYears();
    const currentYear = new Date().getFullYear();
    this.fetchClubsByYear(currentYear);
  },
  computed: {
    getTypeText() {
      return (type) => {
        switch (type) {
          case 1:
            return '思想政治类';
          case 2:
            return '学术科技类';
          case 3:
            return '体育竞技类';
          case 4:
            return '志愿公益类';
          case 5:
            return '文化艺术类';
          default:
            return '';
        }
      };
    },
  },
  methods: {
    updateHoverPosition(event) {
      const offset = 10; // 偏移量，确保图表不会覆盖到鼠标指针
      let left = event.clientX + offset;
      let top = event.clientY + offset;

      // 确保图表不会超出视窗范围
      if (left + 300 > window.innerWidth) {
        left = event.clientX - 300 - offset;
      }
      if (top + 300 > window.innerHeight) {
        top = event.clientY - 300 - offset;
      }

      this.hoverPosition = {
        top,
        left
      };
    },
    fetchYears() {
      axios.get('/statistics')
        .then(response => {
          this.years = response.data.data.years;
          this.selectedYear = this.years[0];
          this.fetchData();
        })
        .catch(error => {
          console.error('Error fetching years:', error);
        });
    },
    fetchData() {
      axios.get(`/statistics`)
        .then(response => {
          this.updateLineCharts(response.data.data);
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    },
    updateLineCharts(data) {
      this.initLineChart('line-chart-clubs', data.years, data.clubsData, '每年社团数量');
      this.initLineChart('line-chart-activities', data.years, data.activitiesData, '每年活动数量');
    },
    initLineChart(id, years, data, title) {
      const chartDom = document.getElementById(id);
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: title,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: years
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: data,
            type: 'line'
          }
        ]
      };
      myChart.setOption(option);
      myChart.on('click', (params) => {
        if (id === 'line-chart-clubs') {
          this.fetchClubsByYear(params.name);
        } else {
          this.fetchActivitiesByYear(params.name);
        }
      });
    },
    fetchClubsByYear(year) {
      axios.get(`/clubs/${year}`)
        .then(response => {
          this.clubs = response.data.data;
          this.showClubsTable = true;
          this.showActivitiesTable = false;
          this.showClubDetails = false;
          this.showActivityDetails = false;
          this.updateClubTypeAndSizeCharts();
        })
        .catch(error => {
          console.error('Error fetching clubs by year:', error);
        });
    },
    fetchActivitiesByYear(year) {
      axios.get(`/activities/${year}`)
        .then(response => {
          this.activities = response.data.data;
          this.showClubsTable = false;
          this.showActivitiesTable = true;
          this.showClubDetails = false;
          this.showActivityDetails = false;
          this.updateActivityTypeAndSizeCharts();
        })
        .catch(error => {
          console.error('Error fetching activities by year:', error);
        });
    },
    updateClubDetailsCharts(club) {
      console.log(club)
      this.initPieChart('club-gender-pie', club.GenderCount, '性别比例');
      this.initPieChart('club-grade-pie', club.GradeCount, '年级分布');
      this.initPieChart('club-party-pie', club.PoliticsCount, '党员占比');
      this.initPieChart('club-major-pie', club.MajorCount, '专业分布');
      // this.initLineChart('club-yearly-line', Object.keys(club.yearly_count), Object.values(club.yearly_count), '社团成员数随时间的分布');
    },
    updateActivityDetailsCharts(activity) {
      this.initPieChart('activity-gender-pie', activity.GenderCount, '性别比例');
      this.initPieChart('activity-grade-pie', activity.GradeCount, '年级分布');
      this.initPieChart('activity-party-pie', activity.PoliticsCount, '党员占比');
      this.initPieChart('activity-major-pie', activity.MajorCount, '专业分布');
    },
    updateClubTypeAndSizeCharts() {
      const clubTypes = this.clubs.reduce((acc, club) => {
        const type = this.getTypeText(club.Type);
        acc[type] = (acc[type] || 0) + 1;
        return acc;
      }, {});
      const clubSizes = this.clubs.reduce((acc, club) => {
        const size = club.Size;
        if (size < 10) {
          acc['<10'] = (acc['<10'] || 0) + 1;
        } else if (size < 50) {
          acc['10-49'] = (acc['10-49'] || 0) + 1;
        } else if (size < 100) {
          acc['50-99'] = (acc['50-99'] || 0) + 1;
        } else {
          acc['>=100'] = (acc['>=100'] || 0) + 1;
        }
        return acc;
      }, {});

      this.initPieChart('club-type-pie', clubTypes, '社团类型分布');
      this.initPieChart('club-size-pie', clubSizes, '社团规模分布');
    },
    updateActivityTypeAndSizeCharts() {
      const activityTypes = this.activities.reduce((acc, activity) => {
        const type = this.getTypeText(activity.Type);
        acc[type] = (acc[type] || 0) + 1;
        return acc;
      }, {});
      const activitySizes = this.activities.reduce((acc, activity) => {
        const size = activity.Size;
        if (size < 10) {
          acc['<10'] = (acc['<10'] || 0) + 1;
        } else if (size < 50) {
          acc['10-49'] = (acc['10-49'] || 0) + 1;
        } else if (size < 100) {
          acc['50-99'] = (acc['50-99'] || 0) + 1;
        } else {
          acc['>=100'] = (acc['>=100'] || 0) + 1;
        }
        return acc;
      }, {});

      this.initPieChart('activity-type-pie', activityTypes, '活动类型分布');
      this.initPieChart('activity-size-pie', activitySizes, '活动规模分布');
    },
    initPieChart(id, data, title) {
      this.$nextTick(() => {
        const chartDom = document.getElementById(id);
        if (!chartDom) {
          console.error(`Element with id ${id} not found`);
          return;
        }
        let myChart = echarts.getInstanceByDom(chartDom);
        if (myChart) {
          myChart.dispose();
        }
        myChart = echarts.init(chartDom);
        const option = {
          title: {
            text: title,
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          series: [
            {
              name: title,
              type: 'pie',
              // radius: '50%',
              radius: ['40%', '70%'], // 调整饼图半径
              data: Object.keys(data).map(key => ({ value: data[key], name: key })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)',
                position: 'inside',
                fontSize: 12 // 调整标签字体大小
              },
              // labelLine: {
              //   show: true,
              //   length: 5, // 调整标签线的长度
              //   length2: 5
              // },
            }
          ]
        };
        myChart.setOption(option);
      });
    }
  }
};
</script>

<style scoped>
#charts {
  display: flex;
  justify-content: space-between;
}

#tables {
  margin-top: 20px;
  display: flex;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
}

th {
  background-color: #f2f2f2;
}

#club-table {
  display: flex;
  width: 200%;
}
#activity-table {
  display: flex;
  width: 200%;
}
.hover-panel {
  position: absolute;
  background-color: rgb(255, 255, 255);
  /* border: 1px solid #ddd; */
  z-index: 100;
}
.chart {
  width: 300px;
  height: 300px;
  /* display: inline-block;
  vertical-align: top; */
  /* flexDirection: 'column', */
  /* padding: 10px;
  margin: 10px;
  box-sizing: border-box; */
}
</style>
